package net.mayee.alice.web.controller.validator.account;

import net.mayee.alice.entity.admin.account.User;
import net.mayee.alice.web.controller.validator.base.BaseValidator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import java.util.regex.Pattern;


public class UserValidator extends BaseValidator implements Validator {

	private static final Pattern LOGINNAME_PATTERN = Pattern
			.compile("^([a-zA-Z0-9]{4,20})$");
	private static final Pattern PASSWORD_PATTERN = Pattern
			.compile("^([a-zA-Z0-9_]{4,16})$");

	@Override
	public boolean supports(Class<?> clazz) {
		return User.class == clazz;
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmpty(errors, "loginName",
				"com.lusoon.error.data_error");
		ValidationUtils.rejectIfEmpty(errors, "plainPassword",
				"com.lusoon.error.data_error");
		ValidationUtils.rejectIfEmpty(errors, "name",
				"com.lusoon.error.data_error");
		ValidationUtils.rejectIfEmpty(errors, "email",
				"com.lusoon.error.data_error");

		User user = (User) target;

		if (!LOGINNAME_PATTERN.matcher(user.getLoginName()).matches()) {
			errors.rejectValue("loginName", "com.lusoon.error.data_error");
		}

		if (!PASSWORD_PATTERN.matcher(user.getPlainPassword()).matches()) {
			errors.rejectValue("plainPassword", "com.lusoon.error.data_error");
		}

		if (user.getName().length() > 10) {
			errors.rejectValue("name", "com.lusoon.error.data_error");
		}

		if (!EMAIL_PATTERN.matcher(user.getEmail()).matches()) {
			errors.rejectValue("email", "com.lusoon.error.data_error");
		}

	}

}
